//
//  XMLUserAcountViewModel.swift
//  Weibo
//
//  Created by mac on 16/5/12.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class XMLUserAcountViewModel: NSObject {

    static let sharedUserAcountViewModel :XMLUserAcountViewModel = XMLUserAcountViewModel()
    
    override init() {
        super.init()
        userAcount = XMLUserAcount.loadUserAcount()
    }
    /// ?????
    var isLogin :Bool {
    
        return accessToken != nil
    }
    var accessToken :String? {
    
        guard let token = userAcount?.access_token else {
        
            return nil
        }
        
        let result = userAcount?.expiresDate?.compare(NSDate())
        if result == NSComparisonResult.OrderedDescending {
        
            return token
        } else {
        
            return nil
        }
    }
    
    var userAcount :XMLUserAcount?//?
    
    func requestAccessToken(code :String, complete :(isSuccess :Bool)->()) {
        
        XMLNetWorkTools.sharedTools.requestAccessToken(code) { (response, error) -> () in
            if error != nil {
                print("网络请求异常")
                complete(isSuccess: false)
                return
            }
            
            guard let dict = response as? [String :AnyObject] else {
                complete(isSuccess: false)
                return
            }
            
            let userAcount = XMLUserAcount(dict: dict)
            self.requestUserInfo(userAcount,complete: complete)
        }
    }
    
    func requestUserInfo(userAcount: XMLUserAcount, complete :(isSuccess :Bool)->()) {
        
        XMLNetWorkTools.sharedTools.requestUserInfo(userAcount) { (response, error) -> () in
            if error != nil {
                print("网络下载异常")
                complete(isSuccess: false)
                return
            }
            guard let dict = response as? [String :AnyObject] else {
                complete(isSuccess: false)
                return
            }
            userAcount.name = dict["name"] as? String
            userAcount.avatar_large = dict["avatar_large"] as? String
            self.userAcount = userAcount
            print(userAcount.name,userAcount.avatar_large)
            let result = userAcount.saveUserAcount()
            if result {
            
                complete(isSuccess: true)
            } else {
            
                complete(isSuccess: false)
            }
        }
    }
}
